package com.linkmed.storage.utils;

import com.obs.services.ObsClient;
import com.obs.services.model.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Semaphore;

public class DeleteFolderTask implements Runnable{

    private static Logger logger = LoggerFactory.getLogger(DeleteFolderTask.class);


    private  String bucketName;

    private  Integer pageNum;

    private String prefix;

    private ObsClient obsClient;

    private Semaphore semaphore;

    public DeleteFolderTask (ObsClient obsClient,String prefix,String bucketName,Integer pageNum,Semaphore semaphore){
        this.prefix = prefix;
        this.obsClient = obsClient;
        this.bucketName = bucketName;
        this.pageNum =pageNum;
        this.semaphore = semaphore;
    }

    @Override
    public void run() {
        ListObjectsRequest request = new ListObjectsRequest(bucketName);
        request.setMaxKeys(pageNum);
        request.setPrefix(prefix);

        ObjectListing result = null;

        DeleteObjectsResult deleteResult = null;
        DeleteObjectsRequest delteRequest = new DeleteObjectsRequest(bucketName);
        do {
            logger.info("正在遍历{}文件夹下的文件",prefix);
            List<KeyAndVersion> toDelete = new ArrayList<KeyAndVersion>();
            result = obsClient.listObjects(request);
            for(ObsObject obsObject : result.getObjects())
            {
                //deleteCount++;
                toDelete.add(new KeyAndVersion(obsObject.getObjectKey()));
               // logger.info("添加删除的文件{}",obsObject.getObjectKey());
            }
            if(toDelete.size()>0){
                delteRequest.setKeyAndVersions(toDelete.toArray(new KeyAndVersion[toDelete.size()]));
                deleteResult = obsClient.deleteObjects(delteRequest);
                // logger.info("删除文件返回结果{}",deleteResult.getDeletedObjectResults());
                if(deleteResult.getErrorResults().size()>0){
                    logger.info("删除文件出现异常文件{}",deleteResult.getErrorResults());
                }

            }


        }while (result.isTruncated());
        semaphore.release();
    }
}
